<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Evaluating Expressions &middot; Crafting Interpreters</title>

<!-- Tell mobile browsers we're optimized for them and they don't need to crop
     the viewport. -->
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" type="text/css" href="style.css" />

<!-- Oh, God, Source Code Pro is so beautiful it makes me want to cry. -->
<link href='https://fonts.googleapis.com/css?family=Source+Code+Pro:400|Source+Sans+Pro:300,400,600' rel='stylesheet' type='text/css'>

<link rel="icon" type="image/png" href="image/favicon.png" />
<script src="jquery-3.4.1.min.js"></script>
<script src="script.js"></script>

<!-- Google analytics -->
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-42804721-2', 'auto');
  ga('send', 'pageview');
</script>

</head>
<body id="top">

<!-- <div class="scrim"></div> -->
<nav class="wide">
  <a href="/"><img src="image/logotype-small.png" title="Crafting Interpreters"></a>
  <div class="contents">
<!-- If there is a part, it must be a chapter within a part. -->
<h3><a href="#top">Evaluating Expressions<small>7</small></a></h3>

<ul>
    <li><a href="#representing-values"><small>7.1</small> Representing Values</a></li>
    <li><a href="#evaluating-expressions"><small>7.2</small> Evaluating Expressions</a></li>
    <li><a href="#runtime-errors"><small>7.3</small> Runtime Errors</a></li>
    <li><a href="#hooking-up-the-interpreter"><small>7.4</small> Hooking Up the Interpreter</a></li>
    <li class="divider"></li>
    <li class="end-part"><a href="#challenges">Challenges</a></li>
    <li class="end-part"><a href="#design-note"><small>note</small>Static and Dynamic Typing</a></li>
</ul>


<div class="prev-next">
    <a href="parsing-expressions.html" title="Parsing Expressions" class="left">&larr;&nbsp;Previous</a>
    <a href="a-tree-walk-interpreter.html" title="A Tree-Walk Interpreter">&uarr;&nbsp;Up</a>
    <a href="statements-and-state.html" title="Statements and State" class="right">Next&nbsp;&rarr;</a>
</div>  </div>
</nav>

<nav class="narrow">
<a href="/"><img src="image/logotype-small.png" title="Crafting Interpreters"></a>
<a href="parsing-expressions.html" title="Parsing Expressions" class="prev">←</a>
<a href="statements-and-state.html" title="Statements and State" class="next">→</a>
</nav>

<div class="page">
<div class="nav-wrapper">
<nav class="floating">
  <a href="/"><img src="image/logotype-small.png" title="Crafting Interpreters"></a>
  <div class="expandable">
<!-- If there is a part, it must be a chapter within a part. -->
<h3><a href="#top">Evaluating Expressions<small>7</small></a></h3>

<ul>
    <li><a href="#representing-values"><small>7.1</small> Representing Values</a></li>
    <li><a href="#evaluating-expressions"><small>7.2</small> Evaluating Expressions</a></li>
    <li><a href="#runtime-errors"><small>7.3</small> Runtime Errors</a></li>
    <li><a href="#hooking-up-the-interpreter"><small>7.4</small> Hooking Up the Interpreter</a></li>
    <li class="divider"></li>
    <li class="end-part"><a href="#challenges">Challenges</a></li>
    <li class="end-part"><a href="#design-note"><small>note</small>Static and Dynamic Typing</a></li>
</ul>


<div class="prev-next">
    <a href="parsing-expressions.html" title="Parsing Expressions" class="left">&larr;&nbsp;Previous</a>
    <a href="a-tree-walk-interpreter.html" title="A Tree-Walk Interpreter">&uarr;&nbsp;Up</a>
    <a href="statements-and-state.html" title="Statements and State" class="right">Next&nbsp;&rarr;</a>
</div>  </div>
  <a id="expand-nav">≡</a>
</nav>
</div>

<article class="chapter">

  <div class="number">7</div>
  <h1>Evaluating Expressions</h1>

<div class="sign-up closable">
  <h1>This book is a work in progress!</h1>
    <span class="dismiss">&times;</span>
    <p>If you see a mistake, find something unclear, or have a suggestion, please <a href="https://github.com/munificent/craftinginterpreters/issues" target="_blank">let me know</a>. To follow its progress, please join the mailing list:</p>

  <!-- Begin MailChimp Signup Form -->
  <div id="mc_embed_signup">
  <form action="//gameprogrammingpatterns.us7.list-manage.com/subscribe/post?u=0952ca43ed2536d6717766b88&amp;id=6e96334109" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
    <input type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="Your email address" required>
    <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
    <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_0952ca43ed2536d6717766b88_6e96334109" tabindex="-1" value=""></div>
    <input type="submit" value="Sign me up!" name="subscribe" id="mc-embedded-subscribe" class="button">
  </form>
  </div>
  <!--End mc_embed_signup-->
  <p class="small">(I post about once a month. Don&#8217;t worry, I won&#8217;t spam you.)</p>
</div>

<blockquote>
<p>You are my creator, but I am your master; Obey!</p>
<p><cite>Mary Shelley, <em>Frankenstein</em></cite></p>
</blockquote>
<p>If you want to properly set the mood for this chapter, try to conjure up a
thunderstorm, one of those swirling tempests that likes to yank open shutters at
the climax of the story. Maybe toss in a few bolts of lightning. In this
chapter, our interpreter will take breath, open its eyes, and execute some code.</p>
<p><span name="spooky"></span></p><img src="image/evaluating-expressions/lightning.png" alt="A bolt of lightning strikes a Victorian mansion. Spooky!" />
<aside name="spooky">
<p>A decrepit Victorian mansion is optional, but adds to the ambiance.</p>
</aside>
<p>There are all manner of ways that language implementations make a computer do
what the user&rsquo;s source code commands. They can compile it to machine code,
translate it to another high level language, or reduce it to some bytecode
format for a virtual machine to run. For our first interpreter, though, we are
going to take the simplest, shortest path and execute the syntax tree itself.</p>
<p>Right now, our parser only supports expressions. So, to &ldquo;execute&rdquo; code, we will
evaluate the expression and produce a value. For each kind of expression syntax
we can parse<span class="em">&mdash;</span>literal, operator, etc.<span class="em">&mdash;</span>we need a corresponding chunk of code
that knows how to evaluate that tree and produce a result. That raises two
questions:</p>
<ol>
<li>
<p>What kinds of values do we produce?</p>
</li>
<li>
<p>How do we organize those chunks of code?</p>
</li>
</ol>
<p>Taking them on one at a time&hellip;</p>
<h2><a href="#representing-values" name="representing-values"><small>7&#8202;.&#8202;1</small>Representing Values</a></h2>
<p>In Lox, <span name="value">values</span> are created by literals, computed by
expressions, and stored in variables. The user sees these as <em>Lox</em> objects, but
they are implemented in the underlying language our interpreter is written in.
That means bridging the lands of Lox&rsquo;s dynamic typing and Java&rsquo;s static types. A
variable in Lox can store a value of any (Lox) type, and can even store values
of different types at different points in time. What Java type might we use to
represent that?</p>
<aside name="value">
<p>Here, I&rsquo;m using &ldquo;value&rdquo; and &ldquo;object&rdquo; pretty much interchangeably.</p>
<p>Later in the C interpreter we&rsquo;ll make a slight distinction between them, but
that&rsquo;s mostly to have unique terms for two different corners of the
implementation<span class="em">&mdash;</span>in-place versus heap-allocated data. From the user&rsquo;s
perspective, the terms are synonymous.</p>
</aside>
<p>Given a Java variable with that static type, we must also be able to determine
which kind of value it holds at runtime. When the interpreter executes a <code>+</code>
operator, it needs to tell if it is adding two numbers or concatenating two
strings. Is there a Java type that can hold numbers, strings, Booleans, and
more? Is there one that can tell us what its runtime type is? There is! Good old
java.lang.Object.</p>
<p>In places in the interpreter where we need to store a Lox value, we can use
Object as the type. Java has boxed versions of its primitive types that all
subclass Object, so we can use those for Lox&rsquo;s built-in types:</p><table>
<thead>
<tr>
  <td>Lox type</td>
  <td>Java representation</td>
</tr>
</thead>
<tbody>
<tr>
  <td>Any Lox value</td>
  <td>Object</td>
</tr>
<tr>
  <td><code>nil</code></td>
  <td><code>null</code></td>
</tr>
<tr>
  <td>Boolean</td>
  <td>Boolean</td>
</tr>
<tr>
  <td>number</td>
  <td>Double</td>
</tr>
<tr>
  <td>string</td>
  <td>String</td>
</tr>
</tbody>
</table>
<p>Given a value of static type Object, we can determine if the runtime value is a
number or a string or whatever using Java&rsquo;s built-in <code>instanceof</code> operator. In
other words, the <span name="jvm">JVM</span>&rsquo;s own object representation
conveniently gives us everything we need to implement Lox&rsquo;s built-in types.
We&rsquo;ll have to do a little more work later when we add Lox&rsquo;s notions of
functions, classes, and instances, but Object and the boxed primitive classes
are sufficient for the types we need right now.</p>
<aside name="jvm">
<p>Another thing we need to do with values is manage their memory, and Java does
that too. A handy object representation and a really nice garbage collector are
the main reasons we&rsquo;re writing our first interpreter in Java.</p>
</aside>
<h2><a href="#evaluating-expressions" name="evaluating-expressions"><small>7&#8202;.&#8202;2</small>Evaluating Expressions</a></h2>
<p>Next, we need blobs of code to implement the evaluation logic for each kind of
expression we can parse. We could stuff those into the syntax tree classes
directly in something like an <code>interpret()</code> method. In effect, we could tell
each syntax tree node, &ldquo;Interpret thyself.&rdquo; This is the Gang of Four&rsquo;s
<a href="https://en.wikipedia.org/wiki/Interpreter_pattern">Interpreter design pattern</a>. It&rsquo;s a neat pattern, but like I mentioned
earlier, it gets messy if we jam all sorts of logic into the tree classes.</p>
<p>Instead, we&rsquo;re going to reuse our groovy <a href="representing-code.html#the-visitor-pattern">Visitor pattern</a>. In the previous
chapter, we created an AstPrinter class. It took in a syntax tree and
recursively traversed it, building up a string which it ultimately returned.
That&rsquo;s almost exactly what a real interpreter does, except instead of
concatenating strings, it computes values.</p>
<p>We start with a new class.</p>
<div class="codehilite"><div class="source-file"><em>lox/Interpreter.java</em><br>
create new file</div>
<pre>
<span class="k">package</span> <span class="i">com.craftinginterpreters.lox</span>;

<span class="k">class</span> <span class="t">Interpreter</span> <span class="k">implements</span> <span class="t">Expr</span>.<span class="t">Visitor</span>&lt;<span class="t">Object</span>&gt; {
}
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, create new file</div>

<p>It declares that it&rsquo;s a visitor. The return type of the visit methods is Object,
the root class that we use to refer to a Lox value in our Java code. To satisfy
the Visitor interface, we need to define visit methods for each of the four
expression tree classes our parser produces. We&rsquo;ll start with the simplest&hellip;</p>
<h3><a href="#evaluating-literals" name="evaluating-literals"><small>7&#8202;.&#8202;2&#8202;.&#8202;1</small>Evaluating literals</a></h3>
<p>The leaves of an expression tree<span class="em">&mdash;</span>the atomic bits of syntax that all other
expressions are composed of<span class="em">&mdash;</span>are <span name="leaf">literals</span>. Literals
are almost values already, but the distinction is important. A literal is a <em>bit
of syntax</em> that produces a value. A literal always appears somewhere in the
user&rsquo;s source code. Lots of values are produced by computation and don&rsquo;t exist
anywhere in the code itself. Those aren&rsquo;t literals. A literal comes from the
parser&rsquo;s domain. Values are an interpreter concept, part of the runtime&rsquo;s world.</p>
<aside name="leaf">
<p>In the <a href="statements-and-state.html">next chapter</a>, when we implement variables, we&rsquo;ll add identifier
expressions, which are also leaf nodes.</p>
</aside>
<p>So, much like we converted a literal <em>token</em> into a literal <em>syntax tree node</em>
in the parser, now we convert the literal tree node into a runtime value. That
turns out to be trivial.</p>
<div class="codehilite"><div class="source-file"><em>lox/Interpreter.java</em><br>
in class <em>Interpreter</em></div>
<pre>
  <span class="a">@Override</span>
  <span class="k">public</span> <span class="t">Object</span> <span class="i">visitLiteralExpr</span>(<span class="t">Expr</span>.<span class="t">Literal</span> <span class="i">expr</span>) {
    <span class="k">return</span> <span class="i">expr</span>.<span class="i">value</span>;
  }
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, in class <em>Interpreter</em></div>

<p>We eagerly produced the runtime value way back during scanning and stuffed it in
the token. The parser took that value and stuck it in the literal tree node,
so to evaluate a literal, we simply pull it back out.</p>
<h3><a href="#evaluating-parentheses" name="evaluating-parentheses"><small>7&#8202;.&#8202;2&#8202;.&#8202;2</small>Evaluating parentheses</a></h3>
<p>The next simplest node to evaluate is grouping<span class="em">&mdash;</span>the node you get as a result
of using explicit parentheses in an expression.</p>
<div class="codehilite"><div class="source-file"><em>lox/Interpreter.java</em><br>
in class <em>Interpreter</em></div>
<pre>
  <span class="a">@Override</span>
  <span class="k">public</span> <span class="t">Object</span> <span class="i">visitGroupingExpr</span>(<span class="t">Expr</span>.<span class="t">Grouping</span> <span class="i">expr</span>) {
    <span class="k">return</span> <span class="i">evaluate</span>(<span class="i">expr</span>.<span class="i">expression</span>);
  }
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, in class <em>Interpreter</em></div>

<p>A <span name="grouping">grouping</span> node has a reference to an inner node
for the expression contained inside the parentheses. To evaluate the grouping
expression itself, we recursively evaluate that subexpression and return it.</p>
<p>We rely on this helper method which simply sends the expression back into the
interpreter&rsquo;s visitor implementation:</p>
<aside name="grouping">
<p>Some parsers don&rsquo;t define tree nodes for parentheses. Instead, when parsing a
parenthesized expression, they simply return the node for the inner expression.
We do create a node for parentheses in Lox because we&rsquo;ll need it later to
correctly handle the left-hand sides of assignment expressions.</p>
</aside>
<div class="codehilite"><div class="source-file"><em>lox/Interpreter.java</em><br>
in class <em>Interpreter</em></div>
<pre>
  <span class="k">private</span> <span class="t">Object</span> <span class="i">evaluate</span>(<span class="t">Expr</span> <span class="i">expr</span>) {
    <span class="k">return</span> <span class="i">expr</span>.<span class="i">accept</span>(<span class="k">this</span>);
  }
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, in class <em>Interpreter</em></div>

<h3><a href="#evaluating-unary-expressions" name="evaluating-unary-expressions"><small>7&#8202;.&#8202;2&#8202;.&#8202;3</small>Evaluating unary expressions</a></h3>
<p>Like grouping, unary expressions have a single subexpression that we must
evaluate first. The difference is that the unary expression itself does a little
work afterwards.</p>
<div class="codehilite"><div class="source-file"><em>lox/Interpreter.java</em><br>
add after <em>visitLiteralExpr</em>()</div>
<pre>
  <span class="a">@Override</span>
  <span class="k">public</span> <span class="t">Object</span> <span class="i">visitUnaryExpr</span>(<span class="t">Expr</span>.<span class="t">Unary</span> <span class="i">expr</span>) {
    <span class="t">Object</span> <span class="i">right</span> = <span class="i">evaluate</span>(<span class="i">expr</span>.<span class="i">right</span>);

    <span class="k">switch</span> (<span class="i">expr</span>.<span class="i">operator</span>.<span class="i">type</span>) {
      <span class="k">case</span> <span class="i">MINUS</span>:
        <span class="k">return</span> -(<span class="t">double</span>)<span class="i">right</span>;
    }

    <span class="c">// Unreachable.</span>
    <span class="k">return</span> <span class="k">null</span>;
  }
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, add after <em>visitLiteralExpr</em>()</div>

<p>First, we evaluate the operand expression. Then we apply the unary operator
itself to the result of that. There are two different unary expressions,
identified by the type of the operator token.</p>
<p>Shown here is <code>-</code>, which negates the result of the subexpression. The
subexpression must be a number. Since we don&rsquo;t <em>statically</em> know that in Java,
we <span name="cast">cast</span> it before performing the operation. This type
cast happens at runtime when the <code>-</code> is evaluated. That&rsquo;s the core of what makes
a language dynamically typed right there.</p>
<aside name="cast">
<p>You&rsquo;re probably wondering what happens if the cast fails. Fear not, we&rsquo;ll get
into that soon.</p>
</aside>
<p>You can start to see how evaluation recursively traverses the tree. We can&rsquo;t
evaluate the unary operator itself until after we evaluate its operand
subexpression. That means our interpreter is doing a <strong>post-order traversal</strong><span class="em">&mdash;</span>each node evaluates its children before doing its own work.</p>
<p>The other unary operator is logical not.</p>
<div class="codehilite"><pre class="insert-before">
    switch (expr.operator.type) {
</pre><div class="source-file"><em>lox/Interpreter.java</em><br>
in <em>visitUnaryExpr</em>()</div>
<pre class="insert">
      <span class="k">case</span> <span class="i">BANG</span>:
        <span class="k">return</span> !<span class="i">isTruthy</span>(<span class="i">right</span>);
</pre><pre class="insert-after">
      case MINUS:
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, in <em>visitUnaryExpr</em>()</div>

<p>The implementation is simple, but what is this &ldquo;truthy&rdquo; thing about? We need to
make a little side trip to one of the great questions of Western philosophy:
<em>what is truth?</em></p>
<h3><a href="#truthiness-and-falsiness" name="truthiness-and-falsiness"><small>7&#8202;.&#8202;2&#8202;.&#8202;4</small>Truthiness and falsiness</a></h3>
<p>OK, maybe we&rsquo;re not going to really get into the universal question, but at
least inside the world of Lox, we need to decide what happens when you use
something other than <code>true</code> or <code>false</code> in a logic operation like <code>!</code> or any
other place where a Boolean is expected.</p>
<p>We <em>could</em> just say it&rsquo;s an error because we don&rsquo;t roll with implicit
conversions, but most dynamically-typed languages aren&rsquo;t that ascetic. Instead,
they take the universe of values of all types and partition them into two sets,
one of which they define to be &ldquo;true&rdquo;, or &ldquo;truthful&rdquo;, or (my favorite) &ldquo;truthy&rdquo;,
and the rest which are &ldquo;false&rdquo; or &ldquo;falsey&rdquo;. This partitioning is somewhat
arbitrary and gets <span name="weird">weird</span> in a few languages.</p>
<aside name="weird" class="bottom">
<p>In JavaScript, strings are truthy, but empty strings are not. Arrays are truthy
but empty arrays are&hellip; also truthy. The number <code>0</code> is falsey, but the <em>string</em>
<code>"0"</code> is truthy.</p>
<p>In Python, empty strings are falsey like JS, but other empty sequences are
falsey too.</p>
<p>In PHP, both the number <code>0</code> and the string <code>"0"</code> are falsey. Most other
non-empty strings are truthy.</p>
<p>Get all that?</p>
</aside>
<p>Lox follows Ruby&rsquo;s simple rule: <code>false</code> and <code>nil</code> are falsey and everything else
is truthy. We implement that like so:</p>
<div class="codehilite"><div class="source-file"><em>lox/Interpreter.java</em><br>
add after <em>visitUnaryExpr</em>()</div>
<pre>
  <span class="k">private</span> <span class="t">boolean</span> <span class="i">isTruthy</span>(<span class="t">Object</span> <span class="i">object</span>) {
    <span class="k">if</span> (<span class="i">object</span> == <span class="k">null</span>) <span class="k">return</span> <span class="k">false</span>;
    <span class="k">if</span> (<span class="i">object</span> <span class="k">instanceof</span> <span class="t">Boolean</span>) <span class="k">return</span> (<span class="t">boolean</span>)<span class="i">object</span>;
    <span class="k">return</span> <span class="k">true</span>;
  }
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, add after <em>visitUnaryExpr</em>()</div>

<h3><a href="#evaluating-binary-operators" name="evaluating-binary-operators"><small>7&#8202;.&#8202;2&#8202;.&#8202;5</small>Evaluating binary operators</a></h3>
<p>Onto the last expression tree class, binary operators. There&rsquo;s a handful of
them, and we&rsquo;ll start with the arithmetic ones:</p>
<div class="codehilite"><div class="source-file"><em>lox/Interpreter.java</em><br>
add after <em>evaluate</em>()</div>
<pre>
  <span class="a">@Override</span>
  <span class="k">public</span> <span class="t">Object</span> <span class="i">visitBinaryExpr</span>(<span class="t">Expr</span>.<span class="t">Binary</span> <span class="i">expr</span>) {
    <span class="t">Object</span> <span class="i">left</span> = <span class="i">evaluate</span>(<span class="i">expr</span>.<span class="i">left</span>);
    <span class="t">Object</span> <span class="i">right</span> = <span class="i">evaluate</span>(<span class="i">expr</span>.<span class="i">right</span>);<span name="left"> </span>

    <span class="k">switch</span> (<span class="i">expr</span>.<span class="i">operator</span>.<span class="i">type</span>) {
      <span class="k">case</span> <span class="i">MINUS</span>:
        <span class="k">return</span> (<span class="t">double</span>)<span class="i">left</span> - (<span class="t">double</span>)<span class="i">right</span>;
      <span class="k">case</span> <span class="i">SLASH</span>:
        <span class="k">return</span> (<span class="t">double</span>)<span class="i">left</span> / (<span class="t">double</span>)<span class="i">right</span>;
      <span class="k">case</span> <span class="i">STAR</span>:
        <span class="k">return</span> (<span class="t">double</span>)<span class="i">left</span> * (<span class="t">double</span>)<span class="i">right</span>;
    }

    <span class="c">// Unreachable.</span>
    <span class="k">return</span> <span class="k">null</span>;
  }
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, add after <em>evaluate</em>()</div>

<aside name="left">
<p>Did you notice we pinned down a subtle corner of the language semantics here?
In a binary expression, we evaluate the operands in left-to-right order. If
those operands have side effects, that choice is user visible, so this isn&rsquo;t
simply an implementation detail.</p>
<p>If we want our two interpreters to be consistent (hint: we do), we&rsquo;ll need to
make sure clox does the same thing.</p>
</aside>
<p>I think you can figure out what&rsquo;s going on here. The main difference from the
unary negation operator is that we have two operands to evaluate.</p>
<p>I left out one arithmetic operator because it&rsquo;s a little special.</p>
<div class="codehilite"><pre class="insert-before">
    switch (expr.operator.type) {
      case MINUS:
        return (double)left - (double)right;
</pre><div class="source-file"><em>lox/Interpreter.java</em><br>
in <em>visitBinaryExpr</em>()</div>
<pre class="insert">
      <span class="k">case</span> <span class="i">PLUS</span>:
        <span class="k">if</span> (<span class="i">left</span> <span class="k">instanceof</span> <span class="t">Double</span> &amp;&amp; <span class="i">right</span> <span class="k">instanceof</span> <span class="t">Double</span>) {
          <span class="k">return</span> (<span class="t">double</span>)<span class="i">left</span> + (<span class="t">double</span>)<span class="i">right</span>;
        }<span name="plus"> </span>

        <span class="k">if</span> (<span class="i">left</span> <span class="k">instanceof</span> <span class="t">String</span> &amp;&amp; <span class="i">right</span> <span class="k">instanceof</span> <span class="t">String</span>) {
          <span class="k">return</span> (<span class="t">String</span>)<span class="i">left</span> + (<span class="t">String</span>)<span class="i">right</span>;
        }

        <span class="k">break</span>;
</pre><pre class="insert-after">
      case SLASH:
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, in <em>visitBinaryExpr</em>()</div>

<p>The <code>+</code> operator can also be used to concatenate two strings. To handle that, we
don&rsquo;t just assume the operands are a certain type and <em>cast</em> them, we
dynamically <em>check</em> the type and choose the appropriate operation. This is why
we need our object representation to support <code>instanceof</code>.</p>
<aside name="plus">
<p>We could have defined an operator specifically for string concatenation. That&rsquo;s
what Perl (<code>.</code>), Lua (<code>..</code>), Smalltalk (<code>,</code>), Haskell (<code>++</code>) and others do.</p>
<p>I thought it would make Lox a little more approachable to use the same syntax as
Java, JavaScript, Python, and others. This means that the <code>+</code> operator is
<strong>overloaded</strong> to support both adding numbers and concatenating strings. Even in
languages that don&rsquo;t use <code>+</code> for strings, they still often overload it for
adding both integers and floating point numbers.</p>
</aside>
<p>Next up are the comparison operators.</p>
<div class="codehilite"><pre class="insert-before">
    switch (expr.operator.type) {
</pre><div class="source-file"><em>lox/Interpreter.java</em><br>
in <em>visitBinaryExpr</em>()</div>
<pre class="insert">
      <span class="k">case</span> <span class="i">GREATER</span>:
        <span class="k">return</span> (<span class="t">double</span>)<span class="i">left</span> &gt; (<span class="t">double</span>)<span class="i">right</span>;
      <span class="k">case</span> <span class="i">GREATER_EQUAL</span>:
        <span class="k">return</span> (<span class="t">double</span>)<span class="i">left</span> &gt;= (<span class="t">double</span>)<span class="i">right</span>;
      <span class="k">case</span> <span class="i">LESS</span>:
        <span class="k">return</span> (<span class="t">double</span>)<span class="i">left</span> &lt; (<span class="t">double</span>)<span class="i">right</span>;
      <span class="k">case</span> <span class="i">LESS_EQUAL</span>:
        <span class="k">return</span> (<span class="t">double</span>)<span class="i">left</span> &lt;= (<span class="t">double</span>)<span class="i">right</span>;
</pre><pre class="insert-after">
      case MINUS:
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, in <em>visitBinaryExpr</em>()</div>

<p>They are basically the same as arithmetic. The only difference is that where the
arithmetic operators produce a value whose type is the same as the operands
(numbers or strings), the comparison operators always produce a Boolean.</p>
<p>The last pair of operators are equality.</p>
<div class="codehilite"><div class="source-file"><em>lox/Interpreter.java</em><br>
in <em>visitBinaryExpr</em>()</div>
<pre>
      <span class="k">case</span> <span class="i">BANG_EQUAL</span>: <span class="k">return</span> !<span class="i">isEqual</span>(<span class="i">left</span>, <span class="i">right</span>);
      <span class="k">case</span> <span class="i">EQUAL_EQUAL</span>: <span class="k">return</span> <span class="i">isEqual</span>(<span class="i">left</span>, <span class="i">right</span>);
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, in <em>visitBinaryExpr</em>()</div>

<p>Unlike the comparison operators which require numbers, the equality operators
support operands of any type, even mixed ones. You can&rsquo;t ask Lox if 3 is <em>less</em>
than <code>"three"</code>, but you can ask if it&rsquo;s <span name="equal"><em>equal</em></span> to
it.</p>
<aside name="equal">
<p>Spoiler alert: it&rsquo;s not.</p>
</aside>
<p>Like truthiness, the equality logic is hoisted out into a separate method.</p>
<div class="codehilite"><div class="source-file"><em>lox/Interpreter.java</em><br>
add after <em>isTruthy</em>()</div>
<pre>
  <span class="k">private</span> <span class="t">boolean</span> <span class="i">isEqual</span>(<span class="t">Object</span> <span class="i">a</span>, <span class="t">Object</span> <span class="i">b</span>) {
    <span class="k">if</span> (<span class="i">a</span> == <span class="k">null</span> &amp;&amp; <span class="i">b</span> == <span class="k">null</span>) <span class="k">return</span> <span class="k">true</span>;
    <span class="k">if</span> (<span class="i">a</span> == <span class="k">null</span>) <span class="k">return</span> <span class="k">false</span>;

    <span class="k">return</span> <span class="i">a</span>.<span class="i">equals</span>(<span class="i">b</span>);
  }
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, add after <em>isTruthy</em>()</div>

<p>This is one of those corners where the details of how we represent Lox objects
in terms of Java matters. We need to correctly implement <em>Lox&rsquo;s</em> notion of
equality, which may be different from Java&rsquo;s.</p>
<p>Fortunately, the two are pretty similar. Lox doesn&rsquo;t do implicit conversions in
equality and Java does not either. We do have to handle <code>nil</code>/<code>null</code> specially
so that we don&rsquo;t throw a NullPointerException if we try to call <code>equals()</code> on
<code>null</code>. Otherwise, we&rsquo;re fine. Java&rsquo;s <span name="nan"><code>.equals()</code></span> method
on Boolean, Double, and String have the behavior we want for Lox.</p>
<aside name="nan">
<p>What do you expect this to evaluate to:</p>
<div class="codehilite"><pre>
(<span class="n">0</span> / <span class="n">0</span>) == (<span class="n">0</span> / <span class="n">0</span>)
</pre></div>
<p>According to <a href="https://en.wikipedia.org/wiki/IEEE_754">IEEE 754</a>, which specifies the behavior of double precision
numbers, dividing a zero by zero gives you the special <strong>NaN</strong> (&ldquo;not a number&rdquo;)
value. Strangely enough, NaN is <em>not</em> equal to itself.</p>
<p>In Java, the <code>==</code> operator on primitive doubles preserves that behavior, but the
<code>equals()</code> method on the Double class does not. Lox uses the latter, so doesn&rsquo;t
follow IEEE. These kinds of subtle incompatibilities occupy a dismaying fraction
of language implementers&rsquo; lives.</p>
</aside>
<p>And that&rsquo;s it! That&rsquo;s all the code we need to correctly interpret a valid Lox
expression. But what about an <em>invalid</em> one? In particular, what happens when a
subexpression evaluates to an object of the wrong type for the operation being
performed?</p>
<h2><a href="#runtime-errors" name="runtime-errors"><small>7&#8202;.&#8202;3</small>Runtime Errors</a></h2>
<p>I was cavalier about jamming casts in whenever a subexpression produces an
Object and the operator requires it to be a number or a string. Those casts can
fail. Even though the user&rsquo;s code is erroneous, if we want to make a <span
name="fail">usable</span> language, we are responsible for handling that error
gracefully.</p>
<aside name="fail">
<p>We could simply not detect or report a type error at all. This is what C does if
you cast a pointer to some type that doesn&rsquo;t match the data that is actually
being pointed to. C gains flexibility and speed by allowing that, but is
also famously dangerous. Once you misinterpret bits in memory, all bets are off.</p>
<p>Few modern languages accept unsafe operations like this. Instead, most are
<strong>memory safe</strong> and ensure<span class="em">&mdash;</span>through a combination of static and runtime checks<span class="em">&mdash;</span>that a program can never incorrectly interpret the value stored in a piece of
memory.</p>
</aside>
<p>It&rsquo;s time for us to talk about <strong>runtime errors.</strong> I spilled a lot of ink in the
previous chapters talking about error handling, but those were all <em>syntax</em> or
<em>static</em> errors. Those are detected and reported before <em>any</em> code is executed.
Runtime errors are failures that the language semantics demand we detect and
report while the program is running (hence the name).</p>
<p>Right now, if an operand is the wrong type for the operation being performed,
the Java cast will fail and the JVM will throw a ClassCastException. That
unwinds the whole stack and exits the application, vomiting a Java stack trace
onto the user. That&rsquo;s probably not what we want. The fact that Lox is
implemented in Java should be a detail hidden from the user. Instead, we want
them to understand that a <em>Lox</em> runtime error occurred, and give them an error
message relevant to our language and their program.</p>
<p>The Java behavior does have one thing going for it, though<span class="em">&mdash;</span>it correctly stops
executing any code when the error occurs. Let&rsquo;s say the user enters some
expression like:</p>
<div class="codehilite"><pre>
<span class="n">2</span> * (<span class="n">3</span> / -<span class="s">&quot;muffin&quot;</span>)
</pre></div>
<p>You can&rsquo;t negate a <span name="muffin">muffin</span>, so we need to report a
runtime error at that inner <code>-</code> expression. That in turn means we can&rsquo;t evaluate
the <code>/</code> expression since it has no meaningful right operand. Likewise the <code>*</code>.
So when a runtime error occurs deep in some expression, we need to escape all
the way out.</p>
<aside name="muffin">
<p>I don&rsquo;t know, man, <em>can</em> you negate a muffin?</p><img src="image/evaluating-expressions/muffin.png" alt="A muffin, negated.">
</aside>
<p>We could print a runtime error and then abort the process and exit the
application entirely. That has a certain melodramatic flair. Sort of the
programming language interpreter equivalent of a mic drop.</p>
<p>Tempting as that is, we should probably do something a little less cataclysmic.
While a runtime error needs to stop evaluating the expression, it shouldn&rsquo;t kill
the <em>interpreter</em>. If a user is running the REPL and has a typo in a line of
code, they should still be able to keep the session going and enter more code
after that.</p>
<h3><a href="#detecting-runtime-errors" name="detecting-runtime-errors"><small>7&#8202;.&#8202;3&#8202;.&#8202;1</small>Detecting runtime errors</a></h3>
<p>Our tree-walk interpreter evaluates nested expressions using recursive method
calls, and we need to unwind out of all of those. Throwing an exception in Java
is a fine way to accomplish that. However, instead of using Java&rsquo;s own cast
failure, we&rsquo;ll define a Lox-specific one so that we can handle it how we want.</p>
<p>Before we do the cast, we check the object&rsquo;s type ourselves. So, for unary <code>-</code>,
we add:</p>
<div class="codehilite"><pre class="insert-before">
      case MINUS:
</pre><div class="source-file"><em>lox/Interpreter.java</em><br>
in <em>visitUnaryExpr</em>()</div>
<pre class="insert">
        <span class="i">checkNumberOperand</span>(<span class="i">expr</span>.<span class="i">operator</span>, <span class="i">right</span>);
</pre><pre class="insert-after">
        return -(double)right;
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, in <em>visitUnaryExpr</em>()</div>

<p>The code to check the operand is:</p>
<div class="codehilite"><div class="source-file"><em>lox/Interpreter.java</em><br>
add after <em>visitUnaryExpr</em>()</div>
<pre>
  <span class="k">private</span> <span class="t">void</span> <span class="i">checkNumberOperand</span>(<span class="t">Token</span> <span class="i">operator</span>, <span class="t">Object</span> <span class="i">operand</span>) {
    <span class="k">if</span> (<span class="i">operand</span> <span class="k">instanceof</span> <span class="t">Double</span>) <span class="k">return</span>;
    <span class="k">throw</span> <span class="k">new</span> <span class="t">RuntimeError</span>(<span class="i">operator</span>, <span class="s">&quot;Operand must be a number.&quot;</span>);
  }
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, add after <em>visitUnaryExpr</em>()</div>

<p>When the check fails, it throws one of these:</p>
<div class="codehilite"><div class="source-file"><em>lox/RuntimeError.java</em><br>
create new file</div>
<pre>
<span class="k">package</span> <span class="i">com.craftinginterpreters.lox</span>;

<span class="k">class</span> <span class="t">RuntimeError</span> <span class="k">extends</span> <span class="t">RuntimeException</span> {
  <span class="k">final</span> <span class="t">Token</span> <span class="i">token</span>;

  <span class="t">RuntimeError</span>(<span class="t">Token</span> <span class="i">token</span>, <span class="t">String</span> <span class="i">message</span>) {
    <span class="k">super</span>(<span class="i">message</span>);
    <span class="k">this</span>.<span class="i">token</span> = <span class="i">token</span>;
  }
}
</pre></div>
<div class="source-file-narrow"><em>lox/RuntimeError.java</em>, create new file</div>

<p>Unlike the Java cast exception, our <span name="class">class</span> tracks the
token that identifies where in the user&rsquo;s code the runtime error came from. As
with static errors, this helps the user know where to fix their code.</p>
<aside name="class">
<p>I admit the name &ldquo;RuntimeError&rdquo; is confusing since Java defines a
RuntimeException class. An annoying thing about building interpreters is your
names often collide with ones already taken by the implementation language. Just
wait until we support Lox classes.</p>
</aside>
<p>We need similar checking to the binary operators. Since I promised you every
single line of code needed to implement the interpreters, I&rsquo;ll run through them
all.</p>
<p>Greater than:</p>
<div class="codehilite"><pre class="insert-before">
      case GREATER:
</pre><div class="source-file"><em>lox/Interpreter.java</em><br>
in <em>visitBinaryExpr</em>()</div>
<pre class="insert">
        <span class="i">checkNumberOperands</span>(<span class="i">expr</span>.<span class="i">operator</span>, <span class="i">left</span>, <span class="i">right</span>);
</pre><pre class="insert-after">
        return (double)left &gt; (double)right;
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, in <em>visitBinaryExpr</em>()</div>

<p>Greater than or equal to:</p>
<div class="codehilite"><pre class="insert-before">
      case GREATER_EQUAL:
</pre><div class="source-file"><em>lox/Interpreter.java</em><br>
in <em>visitBinaryExpr</em>()</div>
<pre class="insert">
        <span class="i">checkNumberOperands</span>(<span class="i">expr</span>.<span class="i">operator</span>, <span class="i">left</span>, <span class="i">right</span>);
</pre><pre class="insert-after">
        return (double)left &gt;= (double)right;
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, in <em>visitBinaryExpr</em>()</div>

<p>Less than:</p>
<div class="codehilite"><pre class="insert-before">
      case LESS:
</pre><div class="source-file"><em>lox/Interpreter.java</em><br>
in <em>visitBinaryExpr</em>()</div>
<pre class="insert">
        <span class="i">checkNumberOperands</span>(<span class="i">expr</span>.<span class="i">operator</span>, <span class="i">left</span>, <span class="i">right</span>);
</pre><pre class="insert-after">
        return (double)left &lt; (double)right;
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, in <em>visitBinaryExpr</em>()</div>

<p>Less than or equal to:</p>
<div class="codehilite"><pre class="insert-before">
      case LESS_EQUAL:
</pre><div class="source-file"><em>lox/Interpreter.java</em><br>
in <em>visitBinaryExpr</em>()</div>
<pre class="insert">
        <span class="i">checkNumberOperands</span>(<span class="i">expr</span>.<span class="i">operator</span>, <span class="i">left</span>, <span class="i">right</span>);
</pre><pre class="insert-after">
        return (double)left &lt;= (double)right;
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, in <em>visitBinaryExpr</em>()</div>

<p>Subtraction:</p>
<div class="codehilite"><pre class="insert-before">
      case MINUS:
</pre><div class="source-file"><em>lox/Interpreter.java</em><br>
in <em>visitBinaryExpr</em>()</div>
<pre class="insert">
        <span class="i">checkNumberOperands</span>(<span class="i">expr</span>.<span class="i">operator</span>, <span class="i">left</span>, <span class="i">right</span>);
</pre><pre class="insert-after">
        return (double)left - (double)right;
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, in <em>visitBinaryExpr</em>()</div>

<p>Division:</p>
<div class="codehilite"><pre class="insert-before">
      case SLASH:
</pre><div class="source-file"><em>lox/Interpreter.java</em><br>
in <em>visitBinaryExpr</em>()</div>
<pre class="insert">
        <span class="i">checkNumberOperands</span>(<span class="i">expr</span>.<span class="i">operator</span>, <span class="i">left</span>, <span class="i">right</span>);
</pre><pre class="insert-after">
        return (double)left / (double)right;
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, in <em>visitBinaryExpr</em>()</div>

<p>Multiplication:</p>
<div class="codehilite"><pre class="insert-before">
      case STAR:
</pre><div class="source-file"><em>lox/Interpreter.java</em><br>
in <em>visitBinaryExpr</em>()</div>
<pre class="insert">
        <span class="i">checkNumberOperands</span>(<span class="i">expr</span>.<span class="i">operator</span>, <span class="i">left</span>, <span class="i">right</span>);
</pre><pre class="insert-after">
        return (double)left * (double)right;
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, in <em>visitBinaryExpr</em>()</div>

<p>All of those rely on this validator, which is virtually the same as the unary
one.</p>
<div class="codehilite"><div class="source-file"><em>lox/Interpreter.java</em><br>
add after <em>checkNumberOperand</em>()</div>
<pre>
  <span class="k">private</span> <span class="t">void</span> <span class="i">checkNumberOperands</span>(<span class="t">Token</span> <span class="i">operator</span>,
                                   <span class="t">Object</span> <span class="i">left</span>, <span class="t">Object</span> <span class="i">right</span>) {
    <span class="k">if</span> (<span class="i">left</span> <span class="k">instanceof</span> <span class="t">Double</span> &amp;&amp; <span class="i">right</span> <span class="k">instanceof</span> <span class="t">Double</span>) <span class="k">return</span>;
   <span name="operand"> </span>
    <span class="k">throw</span> <span class="k">new</span> <span class="t">RuntimeError</span>(<span class="i">operator</span>, <span class="s">&quot;Operands must be numbers.&quot;</span>);
  }
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, add after <em>checkNumberOperand</em>()</div>

<aside name="operand">
<p>Another subtle semantic choice: We evaluate <em>both</em> operands before checking the
type of <em>either</em>. Imagine we have a function <code>say()</code> that prints its argument
then returns it. In:</p>
<div class="codehilite"><pre>
<span class="i">say</span>(<span class="s">&quot;left&quot;</span>) - <span class="i">say</span>(<span class="s">&quot;right&quot;</span>);
</pre></div>
<p>Our implementation prints both &ldquo;left&rdquo; and &ldquo;right&rdquo; before reporting the runtime
error. We could have instead specified that the left operand is checked before
even evaluating the right.</p>
</aside>
<p>The last remaining operator, again the odd one out, is addition. Since <code>+</code> is
overloaded for numbers and strings, it already has code to check the types. All
we need to do is fail if neither of the two success cases match.</p>
<div class="codehilite"><pre class="insert-before">
          return (String)left + (String)right;
        }

</pre><div class="source-file"><em>lox/Interpreter.java</em><br>
in <em>visitBinaryExpr</em>()<br>
replace 1 line</div>
<pre class="insert">
        <span class="k">throw</span> <span class="k">new</span> <span class="t">RuntimeError</span>(<span class="i">expr</span>.<span class="i">operator</span>,
            <span class="s">&quot;Operands must be two numbers or two strings.&quot;</span>);
</pre><pre class="insert-after">
      case SLASH:
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, in <em>visitBinaryExpr</em>(), replace 1 line</div>

<p>That gets us detecting runtime errors deep in the bowels of the evaluator. The
errors are getting thrown. The next step is to write the code that catches them.
For that, we need to wire up the Interpreter class into the main Lox class that
drives it.</p>
<h2><a href="#hooking-up-the-interpreter" name="hooking-up-the-interpreter"><small>7&#8202;.&#8202;4</small>Hooking Up the Interpreter</a></h2>
<p>The visit methods are sort of the guts of the Interpreter class, where the real
work happens. We need to wrap a skin around them to interface with the rest of
the program. The Interpreter&rsquo;s public API is simply one method:</p>
<div class="codehilite"><div class="source-file"><em>lox/Interpreter.java</em><br>
in class <em>Interpreter</em></div>
<pre>
  <span class="t">void</span> <span class="i">interpret</span>(<span class="t">Expr</span> <span class="i">expression</span>) {<span name="void"> </span>
    <span class="k">try</span> {
      <span class="t">Object</span> <span class="i">value</span> = <span class="i">evaluate</span>(<span class="i">expression</span>);
      <span class="t">System</span>.<span class="i">out</span>.<span class="i">println</span>(<span class="i">stringify</span>(<span class="i">value</span>));
    } <span class="k">catch</span> (<span class="t">RuntimeError</span> <span class="i">error</span>) {
      <span class="t">Lox</span>.<span class="i">runtimeError</span>(<span class="i">error</span>);
    }
  }
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, in class <em>Interpreter</em></div>

<p>This takes in a syntax tree for an expression and evaluates it. If that
succeeds, <code>evaluate()</code> returns an object for the result value. <code>interpret()</code>
converts that to a string and shows it to the user. To convert a Lox value to a
string, we rely on:</p>
<div class="codehilite"><div class="source-file"><em>lox/Interpreter.java</em><br>
add after <em>isEqual</em>()</div>
<pre>
  <span class="k">private</span> <span class="t">String</span> <span class="i">stringify</span>(<span class="t">Object</span> <span class="i">object</span>) {
    <span class="k">if</span> (<span class="i">object</span> == <span class="k">null</span>) <span class="k">return</span> <span class="s">&quot;nil&quot;</span>;

    <span class="k">if</span> (<span class="i">object</span> <span class="k">instanceof</span> <span class="t">Double</span>) {
      <span class="t">String</span> <span class="i">text</span> = <span class="i">object</span>.<span class="i">toString</span>();
      <span class="k">if</span> (<span class="i">text</span>.<span class="i">endsWith</span>(<span class="s">&quot;.0&quot;</span>)) {
        <span class="i">text</span> = <span class="i">text</span>.<span class="i">substring</span>(<span class="n">0</span>, <span class="i">text</span>.<span class="i">length</span>() - <span class="n">2</span>);
      }
      <span class="k">return</span> <span class="i">text</span>;
    }

    <span class="k">return</span> <span class="i">object</span>.<span class="i">toString</span>();
  }
</pre></div>
<div class="source-file-narrow"><em>lox/Interpreter.java</em>, add after <em>isEqual</em>()</div>

<p>This is another of those pieces of code like <code>isTruthy()</code> that crosses the
membrane between the user&rsquo;s view of Lox objects and their internal
representation in Java.</p>
<p>It&rsquo;s pretty straightforward. Since Lox was designed to be familiar to someone
coming from Java, things like Booleans look the same in both languages. The two
edge cases are <code>nil</code>, which we represent using Java&rsquo;s <code>null</code>, and numbers.</p>
<p>Lox uses double-precision numbers even for integer values. In that case, they
should print without a decimal point. Since Java has both floating point and
integer types, it wants you to know which one you&rsquo;re using. It tells you by
adding an explicit <code>.0</code> to integer-valued doubles. We don&rsquo;t care about that, so
we <span name="number">hack</span> it off the end.</p>
<aside name="number">
<p>Yet again, we take care of this edge case with numbers to ensure that jlox and
clox work the same. Handling weird corners of the language like this will drive
you crazy but is an important part of the job.</p>
<p>Users rely on these details<span class="em">&mdash;</span>either deliberately or inadvertently<span class="em">&mdash;</span>and if
the implementations aren&rsquo;t consistent, their program will break when they run it
on different interpreters.</p>
</aside>
<h3><a href="#reporting-runtime-errors" name="reporting-runtime-errors"><small>7&#8202;.&#8202;4&#8202;.&#8202;1</small>Reporting runtime errors</a></h3>
<p>If a runtime error is thrown while evaluating the expression, <code>interpret()</code>
catches it. This lets us report the error to the user and then gracefully
continue. All of our existing error reporting code lives in the Lox class, so we
put this method there too.</p>
<div class="codehilite"><div class="source-file"><em>lox/Lox.java</em><br>
add after <em>error</em>()</div>
<pre>
  <span class="k">static</span> <span class="t">void</span> <span class="i">runtimeError</span>(<span class="t">RuntimeError</span> <span class="i">error</span>) {
    <span class="t">System</span>.<span class="i">err</span>.<span class="i">println</span>(<span class="i">error</span>.<span class="i">getMessage</span>() +
        <span class="s">&quot;</span><span class="e">\n</span><span class="s">[line &quot;</span> + <span class="i">error</span>.<span class="i">token</span>.<span class="i">line</span> + <span class="s">&quot;]&quot;</span>);
    <span class="i">hadRuntimeError</span> = <span class="k">true</span>;
  }
</pre></div>
<div class="source-file-narrow"><em>lox/Lox.java</em>, add after <em>error</em>()</div>

<p>We use the token associated with the RuntimeError to tell the user what line of
code was executing when the error occurred. Even better would be to give the
user an entire call stack to show how they <em>got</em> to be executing that code. But
we don&rsquo;t have function calls yet, so I guess we don&rsquo;t have to worry about it.</p>
<p>After showing the error, <code>runtimeError()</code> sets this field:</p>
<div class="codehilite"><pre class="insert-before">
  static boolean hadError = false;
</pre><div class="source-file"><em>lox/Lox.java</em><br>
in class <em>Lox</em></div>
<pre class="insert">
  <span class="k">static</span> <span class="t">boolean</span> <span class="i">hadRuntimeError</span> = <span class="k">false</span>;

</pre><pre class="insert-after">
  public static void main(String[] args) throws IOException {
</pre></div>
<div class="source-file-narrow"><em>lox/Lox.java</em>, in class <em>Lox</em></div>

<p>That field plays a small but important role.</p>
<div class="codehilite"><pre class="insert-before">
    run(new String(bytes, Charset.defaultCharset()));

    // Indicate an error in the exit code.
    if (hadError) System.exit(65);
</pre><div class="source-file"><em>lox/Lox.java</em><br>
in <em>runFile</em>()</div>
<pre class="insert">
    <span class="k">if</span> (<span class="i">hadRuntimeError</span>) <span class="t">System</span>.<span class="i">exit</span>(<span class="n">70</span>);
</pre><pre class="insert-after">
  }
</pre></div>
<div class="source-file-narrow"><em>lox/Lox.java</em>, in <em>runFile</em>()</div>

<p>If the user is running a Lox <span name="repl">script from a file</span> and a
runtime error occurs, we set an exit code when the process quits to let the
calling process know. Not everyone cares about shell etiquette, but we do.</p>
<aside name="repl">
<p>If the user is running the REPL, we don&rsquo;t care about tracking runtime errors.
After they are reported, we simply loop around and let them input new code and
keep going.</p>
</aside>
<h3><a href="#running-the-interpreter" name="running-the-interpreter"><small>7&#8202;.&#8202;4&#8202;.&#8202;2</small>Running the interpreter</a></h3>
<p>Now that we have an interpreter, the Lox class can start using it.</p>
<div class="codehilite"><pre class="insert-before">
public class Lox {
</pre><div class="source-file"><em>lox/Lox.java</em><br>
in class <em>Lox</em></div>
<pre class="insert">
  <span class="k">private</span> <span class="k">static</span> <span class="k">final</span> <span class="t">Interpreter</span> <span class="i">interpreter</span> = <span class="k">new</span> <span class="t">Interpreter</span>();
</pre><pre class="insert-after">
  static boolean hadError = false;
</pre></div>
<div class="source-file-narrow"><em>lox/Lox.java</em>, in class <em>Lox</em></div>

<p>We make the field static so that successive calls to <code>run()</code> inside a REPL
session reuse the same interpreter. That doesn&rsquo;t make a difference now, but it
will later when the interpreter stores global variables. Those variables should
persist throughout the REPL session.</p>
<p>Finally, we remove the line of temporary code from the <a href="parsing-expressions.html">last chapter</a> for
printing the syntax tree and replace it with this:</p>
<div class="codehilite"><pre class="insert-before">
    // Stop if there was a syntax error.
    if (hadError) return;

</pre><div class="source-file"><em>lox/Lox.java</em><br>
in <em>run</em>()<br>
replace 1 line</div>
<pre class="insert">
    <span class="i">interpreter</span>.<span class="i">interpret</span>(<span class="i">expression</span>);
</pre><pre class="insert-after">
  }
</pre></div>
<div class="source-file-narrow"><em>lox/Lox.java</em>, in <em>run</em>(), replace 1 line</div>

<p>We have an entire language pipeline now: scanning, parsing, and
execution. Congratulations, you now have your very own arithmetic calculator.</p>
<p>As you can see, the interpreter is pretty bare bones. But the Interpreter class
and the visitor pattern we&rsquo;ve set up today form the skeleton that later chapters
will stuff full of interesting guts<span class="em">&mdash;</span>variables, functions, etc. Right now, the
interpreter doesn&rsquo;t do very much, but it&rsquo;s alive!</p><img src="image/evaluating-expressions/skeleton.png" alt="A skeleton waving hello." />
<div class="challenges">
<h2><a href="#challenges" name="challenges">Challenges</a></h2>
<ol>
<li>
<p>Allowing comparisons on types other than numbers could be useful. The
operators might have a reasonable interpretation for strings. Even
comparisons among mixed types, like <code>3 &lt; "pancake"</code> could be handy to enable
things like ordered collections of heterogeneous types. Or it could simply
lead to bugs and confusion.</p>
<p>Would you extend Lox to support comparing other types? If so, which pairs of
types do you allow and how do you define their ordering? Justify your
choices and compare them to other languages.</p>
</li>
<li>
<p>Many languages define <code>+</code> such that if <em>either</em> operand is a string, the
other is converted to a string and the results are then concatenated. For
example, <code>"scone" + 4</code> would yield <code>scone4</code>. Extend the code in
<code>visitBinaryExpr()</code> to support that.</p>
</li>
<li>
<p>What happens right now if you divide a number by zero? What do you think
should happen? Justify your choice. How do other languages you know handle
division by zero and why do they make the choices they do?</p>
<p>Change the implementation in <code>visitBinaryExpr()</code> to detect and report a
runtime error for this case.</p>
</li>
</ol>
</div>
<div class="design-note">
<h2><a href="#design-note" name="design-note">Design Note: Static and Dynamic Typing</a></h2>
<p>Some languages, like Java, are statically typed which means type errors are
detected and reported at compile time before any code is run. Others, like Lox,
are dynamically typed and defer checking for type errors until runtime right
before an operation is attempted. We tend to consider this a black-and-white
choice, but there is actually a continuum between them.</p>
<p>It turns out even most statically-typed languages do <em>some</em> type checks at
runtime. The type system checks most type rules statically, but inserts runtime
checks in the generated code for other operations.</p>
<p>For example, in Java, the <em>static</em> type system assumes a cast expression will
always safely succeed. After you cast some value, you can statically treat it as
the destination type and not get any compile errors. But downcasts can fail,
obviously. The only reason the static checker can presume that casts always
succeed without violating the language&rsquo;s soundness guarantees is because the
cast is checked <em>at runtime</em> and throws an exception on failure.</p>
<p>A more subtle example is <a href="https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)#Covariant_arrays_in_Java_and_C.23">covariant arrays</a> in Java and C#. The static
subtyping rules for arrays allow operations that are not sound. Consider:</p>
<div class="codehilite"><pre>
<span class="t">Object</span>[] <span class="i">stuff</span> = <span class="k">new</span> <span class="t">Integer</span>[<span class="n">1</span>];
<span class="i">stuff</span>[<span class="n">0</span>] = <span class="s">&quot;not an int!&quot;</span>;
</pre></div>
<p>This code compiles without any errors. The first line upcasts the Integer array
and stores it in a variable of type Object array. The second line stores a
string in one of its cells. The Object array type statically allows that<span class="em">&mdash;</span>strings <em>are</em> Objects<span class="em">&mdash;</span>but the actual Integer array that <code>stuff</code> refers to
at runtime should never have a string in it! To avoid that catastrophe, when you
store a value in an array, the JVM does a <em>runtime</em> check to make sure it&rsquo;s an
allowed type. If not, it throws an ArrayStoreException.</p>
<p>Java could have avoided the need to check this at runtime by disallowing the
cast on the first line. It could make arrays <em>invariant</em> such that an array of
Integers is <em>not</em> an array of Objects. That&rsquo;s statically sound, but it prohibits
common and safe patterns of code that only read from arrays. Covariance is safe
if you never <em>write</em> to the array. Those patterns were particularly important
for usability in Java 1.0 before it supported generics.</p>
<p>James Gosling and the other Java designers traded off a little static safety and
performance<span class="em">&mdash;</span>those array store checks take time<span class="em">&mdash;</span>in return for some
flexibility.</p>
<p>There are few modern statically-typed languages that don&rsquo;t make that trade-off
<em>somewhere</em>. Even Haskell will let you run code with non-exhaustive matches. If
you find yourself designing a statically-typed language, keep in mind that you
can sometimes give users more flexibility without sacrificing <em>too</em> many of the
benefits of static safety by deferring some type checks until runtime.</p>
<p>On the other hand, a key reason users choose statically-typed languages is
because of the confidence the language gives them that certain kinds of errors
can <em>never</em> occur when their program is run. Defer too many type checks until
runtime, and you erode that confidence.</p>
</div>

<footer>
<a href="statements-and-state.html" class="next">
  Next Chapter: &ldquo;Statements and State&rdquo; &rarr;
</a>
Handcrafted by Robert Nystrom&ensp;&mdash;&ensp;<a href="https://github.com/munificent/craftinginterpreters/blob/master/LICENSE" target="_blank">&copy; 2015&hairsp;&ndash;&hairsp;2020</a>
</footer>
</article>

</div>
</body>
</html>
